package com.demo.sso.sdk.controller;

import com.demo.sso.sdk.model.SsoUserInfo;
import com.demo.sso.sdk.service.SsoClientService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;

/**
 * SSO回调控制器
 * 处理SSO登录回调和登出请求
 * 
 * @author SpringCloud团队
 * @version 1.0.0
 * @since 2025-01-01
 */
@Controller
public class SsoCallbackController {

    private static final Logger logger = LoggerFactory.getLogger(SsoCallbackController.class);

    @Autowired
    private SsoClientService ssoClientService;

    /**
     * 处理SSO登录回调
     * 
     * @param code 授权码
     * @param state state参数
     * @param request HTTP请求
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("${sso.sdk.callback-path:/sso/callback}")
    public void handleCallback(@RequestParam String code, 
                               @RequestParam String state,
                               HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        logger.info("Received SSO callback with code: {}, state: {}", code, state);

        try {
            // 处理SSO回调
            SsoUserInfo userInfo = ssoClientService.handleCallback(code, state, request);
            
            if (userInfo != null) {
                logger.info("SSO login successful for user: {}", userInfo.getUsername());
                // 登录成功，重定向到首页或原来要访问的页面
                response.sendRedirect("/");
            } else {
                logger.error("SSO login failed: failed to get user info");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "SSO login failed");
            }
        } catch (IllegalArgumentException e) {
            logger.error("Invalid callback parameters", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (Exception e) {
            logger.error("Error processing SSO callback", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "SSO callback processing failed");
        }
    }

    /**
     * 处理登录请求
     * 
     * @param request HTTP请求
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("${sso.sdk.login-path:/login}")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("Redirecting to SSO login page");

        try {
            // 检查用户是否已登录
            if (ssoClientService.isLoggedIn(request)) {
                // 已登录，重定向到首页
                response.sendRedirect("/");
                return;
            }

            // 生成SSO登录URL并重定向
            String loginUrl = ssoClientService.generateLoginUrl(request);
            response.sendRedirect(loginUrl);
        } catch (Exception e) {
            logger.error("Error redirecting to SSO login page", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "SSO service unavailable");
        }
    }

    /**
     * 处理登出请求
     * 
     * @param request HTTP请求
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("${sso.sdk.logout-path:/logout}")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("Processing logout request");

        try {
            // 执行本地登出
            ssoClientService.logout(request);
            
            // 重定向到SSO登出页面
            String logoutUrl = ssoClientService.generateLogoutUrl();
            response.sendRedirect(logoutUrl);
        } catch (Exception e) {
            logger.error("Error processing logout", e);
            // 即使出错也要清除本地session
            ssoClientService.logout(request);
            response.sendRedirect("/");
        }
    }
}